package com.ibl.rover.lite.client;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import com.ibl.rover.lite.client.Activity.CustomerRouteActivity;
import com.ibl.rover.lite.client.Activity.RoverSyncActivity;
import com.ibl.rover.lite.client.Activity.SettingActivity;
import com.ibl.rover.lite.client.Application.ApplicationContext;
import com.ibl.rover.lite.client.Sync.Parser.ResponseHandler;
import com.ibl.rover.lite.client.Sync.Parser.SyncRequestBuilder;
import com.ibl.rover.lite.client.constants.RoverConstants.ServerErrCode;
import com.ibl.rover.lite.client.constants.RoverConstants.SyncProgress;
import com.ibl.rover.lite.common.bean.AppSetupBean;
import com.ibl.rover.lite.common.bean.SettingBean;
import com.ibl.rover.lite.common.bean.UserBean;
import com.ibl.rover.lite.common.db.Criteria;
import com.ibl.rover.lite.common.db.Criteria.Operators;
import com.ibl.rover.lite.common.db.DatabaseManager;
import com.mobile.sync.client.Sync.impl.HTTPSyncImplFactory;
import com.mobile.sync.client.impl.AbstractBean;
import com.mobile.sync.client.impl.RequestBean;
import com.mobile.sync.client.impl.ResponseBean;
import com.ibl.rover.lite.client.Sync.Process.*;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class RoverLiteClientActivity extends Activity implements
		OnClickListener {

	private Logger logger = Logger.getLogger();
	private ApplicationContext context;
	private Resources resources;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		try {
			logger.log("OnCreate Start");
			super.onCreate(savedInstanceState);
			setContentView(R.layout.login);
			context = (ApplicationContext) getApplicationContext();
			((Button) this.findViewById(R.id.login)).setOnClickListener(this);
			((Button) this.findViewById(R.id.cancel_button))
					.setOnClickListener(this);
			resources = getResources();
			UserBean userBean = context.loggedUser;
			if (userBean != null) {
				getCutomerRouteActivity();
			}

			logger.log("OnCreate End");
		} catch (Exception e) {
			logger.logException("OnCreate Exception ", e);
		}

	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.login:
			onLogin();
			break;
		case R.id.cancel_button:
			finish();
			break;
		default:
			break;
		}

	}

	/**
	 * On Login
	 */
	private void onLogin() {
		try {
			logger.log("On Login Start");

			String userName = ((EditText) findViewById(R.id.userName))
					.getText().toString().toUpperCase();
			String password = ((EditText) findViewById(R.id.password))
					.getText().toString();

			context.setHttpSyncImpl(HTTPSyncImplFactory
					.getTransportAgent(context.getAppParams()
							.getHttpConfiguration()));
			context.getHttpSyncImpl().register(
					new ResponseHandler("[RESP_PARSE]"));
			context.initialize(userName);

			markedAsLoggedIn(userName);
			if (!isSyncZero()) {
				SyncRequestBuilder syncRequestBuilder = context
						.getSyncRequestBuilder();

				RequestBean requestBean = syncRequestBuilder
						.buildLoginRequest(userName);

				loginTask authenticationTask = new loginTask(this, context);
				authenticationTask.execute(requestBean);
			} else {
				authenticateUserLocally(userName, password);
			}
			logger.log("On Login End");
		} catch (Exception e) {
			logger.logException("On Login Exception ", e);
		}
	}

	/**
	 * Authenticate User locally
	 */
	private void authenticateUserLocally(String userName, String password) {
		try {
			updateSettings();
			Criteria<UserBean> criteria = context.getDatabaseManager()
					.generateCriteria(UserBean.class);
			criteria.addRestriction(UserBean.COL_USER_NAME, Operators.isEqual,
					userName);
			criteria.addRestrictionWithAnd(UserBean.COL_PASSWORD,
					Operators.isEqual, password);

			if (criteria.execute().size() > 0) {
				Intent intent = new Intent(RoverLiteClientActivity.this,
						CustomerRouteActivity.class);
				startActivity(intent);
			} else {
				showErroDialog(1, "User Password is incorrect.");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void markedAsLoggedIn(final String userName) {
		try {
			FileOutputStream openFileOutput = openFileOutput(
					userName + ".user", MODE_PRIVATE);
			openFileOutput.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	private void getCutomerRouteActivity() {
		try {
			Intent landingPageIntent = new Intent(RoverLiteClientActivity.this,
					CustomerRouteActivity.class);
			startActivity(landingPageIntent);
		} catch (Exception e) {
			logger.logException("Get Customer Route Activity", e);
		}

	}

	private class loginTask extends SyncronizationProcess {

		public loginTask(Context context, ApplicationContext ssaContext) {
			super(context, ssaContext);
		}

		@Override
		public void onResponseComplete(AbstractBean responseMsg) {
			logger.log("[onResponseComplete .. Starts]");
			if (null != responseMsg) {
				ResponseBean httpResponseMsg = (ResponseBean) responseMsg;
				logger.log("[Http Response Code : "
						+ httpResponseMsg.getServerResponseCode());
				logger.log("[Server Response Code : "
						+ httpResponseMsg.getMessage());
				int httpResponseCode = httpResponseMsg.getServerResponseCode();
				if (ResponseBean.HTTP_OK == httpResponseCode) {
					switch (httpResponseMsg.getMessageCode()) {
					case ServerErrCode.SUCCESS:
						doHandleSuccess();
						finish();
						break;
					default:
						doHandleFailure(httpResponseMsg.getMessageCode());
						break;
					}
				} else if (httpResponseCode > 400 && httpResponseCode < 500) {

					//
				} else {
					if (isSyncZero()) {
						try {
							String userName = ((EditText) findViewById(R.id.userName))
									.getText().toString().toUpperCase();
							String password = ((EditText) findViewById(R.id.password))
									.getText().toString();
							updateSettings();
							Criteria<UserBean> criteria = context
									.getDatabaseManager().generateCriteria(
											UserBean.class);
							criteria.addRestriction(UserBean.COL_USER_NAME,
									Operators.isEqual, userName);
							criteria.addRestrictionWithAnd(
									UserBean.COL_PASSWORD, Operators.isEqual,
									password);

							if (criteria.execute().size() > 0) {
								Intent intent = new Intent(
										RoverLiteClientActivity.this,
										CustomerRouteActivity.class);
								startActivity(intent);
							} else {
								showErroDialog(1,
										"Connenctivity to the Server is Unavailble");
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					} else {
						showErroDialog(2,
								"Connection to the Server is not Available");
					}
				}
			}
			logger.log("[onResponseComplete .. Ends]");
		}

		private void doHandleFailure(final int serverErrCode) {
			try {
				if (serverErrCode == 505) {
					showErroDialog(2, "TSO information does Exist.");
				} else {
					showErroDialog(2,
							"Error Occured.Please contact to Adminstrator");
				}
			} catch (Exception e) {
				logger.logException("do Handle Failure Exception", e);
			}
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			switch (values[0]) {
			case SyncProgress.SYNC_SERVER_SUCCESS:
				progress.setMessage(resources
						.getString(R.string.sync_auth_success));
				break;
			case SyncProgress.SYNC_APPSETUP:
				progress.setMessage(resources.getString(R.string.sync_appsetup));
				break;

			case SyncProgress.SYNC_PRODUCT_CATEGORY:
				progress.setMessage(resources
						.getString(R.string.sync_productscategory));
				break;

			case SyncProgress.SYNC_PRODUCTS:
				progress.setMessage(resources.getString(R.string.sync_products));
				break;

			case SyncProgress.SYNC_CUSTOMER:
				progress.setMessage(resources
						.getString(R.string.sync_customers));
				break;

			case SyncProgress.SYNC_ROUTES:
				progress.setMessage(resources.getString(R.string.sync_routes));
				break;
			}
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.login_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.rover_setting:
			showSettingForm();
			return true;

		default:
			return true;
		}
	}

	private void showSettingForm() {
		try {
			Intent intent = new Intent(RoverLiteClientActivity.this,
					SettingActivity.class);
			startActivity(intent);
		} catch (Exception e) {
			logger.logException("sho Setting Exception", e);
		}
	}

	/**
	 * Save Server Setting
	 */
	private void updateSettings() {
		try {

			Criteria<SettingBean> criteria = context.getDatabaseManager()
					.generateCriteria(SettingBean.class);

			List<SettingBean> list = criteria.execute();
			SharedPreferences app_preferences = getSharedPreferences("SETTING",
					MODE_WORLD_WRITEABLE);
			
			
			
			if (list.size() > 0) {
				SettingBean settingBean = list.get(0);
				settingBean.setServerPort(String.valueOf(context.getAppParams()
						.getHttpConfiguration().getServerPort()));
				settingBean.setServerUrl(context.getAppParams()
						.getHttpConfiguration().getServerUrl());

				context.getDatabaseManager().updateBean(settingBean);

			}

		} catch (Exception e) {
			logger.logException("saveSetting ", e);
		}
	}

	private void showErroDialog(final int titleId, final String titleMsg) {
		AlertDialog.Builder errorMsg = new AlertDialog.Builder(this);
		errorMsg.setTitle("Alert");
		errorMsg.setMessage(titleMsg);
		errorMsg.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		});
		errorMsg.show();
	}

	private void doHandleSuccess() {
		logger.log("[doHandleSuccess() .. Starts]");

		String userName = ((EditText) findViewById(R.id.userName)).getText()
				.toString().toUpperCase();
		String password = ((EditText) findViewById(R.id.password)).getText()
				.toString();

		UserBean userBean = new UserBean();
		userBean.setUserName(userName);
		userBean.setPassword(password);
		userBean.setCellNumber("");
		userBean.setContact("");
		userBean.setRole("");
		userBean.setStreetAddress("");
		context.getDatabaseManager().saveBean(userBean);

		context.loggedUser = userBean;

		Intent intent = new Intent(RoverLiteClientActivity.this,
				CustomerRouteActivity.class);
		startActivity(intent);

		logger.log("doHandleSuccess() .. Ends");
	}

	private boolean isSyncZero() {
		try {
			DatabaseManager entityMgr = context.getDatabaseManager();
			List<AppSetupBean> list = entityMgr.findAllBean(AppSetupBean.class);
			if (list.size() > 0)
				return true;

		} catch (Exception ex) {
			logger.logException("[Exception occured in isSyncZero]", ex);
		}
		return false;
	}
}